package org.wizehack.mri.testSet;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;

import org.wizehack.mri.exception.NotUsedException;
import org.wizehack.mri.exception.ObjectNotFoundException;
import org.wizehack.mri.test.TestCase;
import org.wizehack.mri.test.TestSuite;

public class VectorBasedStrategy extends TestCaseReduction {

	public VectorBasedStrategy() {
		super();
	}

	/**
	 * this method deletes testcases in the given testsuite if they are included in the deleteList.
	 * @param testSuite
	 * @param deleteList
	 * @return
	 */
	protected TestSuite deleteEmenets(TestSuite testSuite, List<TestCase> deleteList) {
		TestSuite tSuite = testSuite;
		for(int i=0; i<tSuite.size(); i++){
			if(deleteList.contains(tSuite.get(i))){
				tSuite.remove(tSuite.get(i));
				i--;
			}
		}
		
		return tSuite;
	}

	@Override
	public TestSuite select() {
		String directory = super.getDirectory();
		List<String> coverageFileList;
		List<String> failedCoverageFileList = super.getFailedCoverageFileList();
		
		if(directory != null){
			coverageFileList = super.scanCoverageFile(directory); 
			System.out.print("Loading coverage files from " + directory + ".....");

		} else {
			throw new InvalidParameterException(directory);
		}

		TestSuite tSuite = setTestResult(coverageFileList, failedCoverageFileList);
		
		List<TestCase> deleteList=null;
		
		if(tSuite != null){
			deleteList = new ArrayList<TestCase>();
			
		} else {
			try {
				throw new ObjectNotFoundException(tSuite);
			} catch (ObjectNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
		for(int i=0; i<tSuite.size()-1; i++){
			TestCase firstTestCase = tSuite.get(i);

			for(int j=i+1; j<tSuite.size(); j++){
				TestCase secondTestCase = tSuite.get(j);

				if(super.isEquivalent(firstTestCase, secondTestCase)){
					
					if( firstTestCase.isPassed() != secondTestCase.isPassed() ){
						
						if( firstTestCase.isPassed() ) {
							deleteList.add(firstTestCase);

						} else {
							deleteList.add(secondTestCase);
						}
					} else {
						deleteList.add(secondTestCase);
					}
				}
			}//end for j
		}// end for i
		
		tSuite = this.deleteEmenets(tSuite, deleteList);
		
		System.out.println("ok");
		return tSuite;
	}



}
